package cn.stockeye.client;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpService {

	private static Log log = LogFactory.getLog(HttpService.class);

	public static final String PROXY_IN_USE = "Y";
	public static final String PROXY_UN_USE = "N";
	private String proxy;
	private String proxyHost;
	private String proxyPort;
	private String proxyProtocol;

	public String getProxyHost() {
		return proxyHost;
	}

	public void setProxyHost(String proxyHost) {
		this.proxyHost = proxyHost;
	}

	public String getProxyPort() {
		return proxyPort;
	}

	public void setProxyPort(String proxyPort) {
		this.proxyPort = proxyPort;
	}

	public String getProxyProtocol() {
		return proxyProtocol;
	}

	public void setProxyProtocol(String proxyProtocol) {
		this.proxyProtocol = proxyProtocol;
	}

	public String getProxy() {
		return proxy;
	}

	public void setProxy(String proxy) {
		this.proxy = proxy;
	}

	/**
	 * 通过代理访问指定url
	 * 
	 * @param url
	 * @param proxyHost
	 * @param proxyPort
	 * @param proxyProtocol
	 * @return
	 */
	public String getResponseViaProxy(String url, String proxyHost,
			String proxyPort, String proxyProtocol) {

		HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort),
				proxyProtocol);

		HttpClient httpClient = new DefaultHttpClient();
		String responseBody = null;
		try {
			httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
					proxy);

			HttpGet httpget = new HttpGet(url);

			log.info("executing request to " + httpget.getURI() + " via "
					+ proxy);
			HttpResponse rsp = httpClient.execute(httpget);
			HttpEntity entity = rsp.getEntity();

			if (entity != null) {
				responseBody = EntityUtils.toString(entity);
			}

		} catch (ClientProtocolException e) {
			log.error(e.getMessage(), e);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return responseBody;
	}

	/**
	 * 不通过代理访问
	 * 
	 * @param url
	 * @return
	 */
	public String getResponse(String url) {
		// 构造HttpClient的实例
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				5000);
		String responseBody = null;
		try {
			HttpGet httpget = new HttpGet(url);
			ResponseHandler<String> responseHandler = new BasicResponseHandler();

			log.info("executing request " + httpget.getURI());

			responseBody = httpClient.execute(httpget, responseHandler);
		} catch (ClientProtocolException e) {
			log.error(e.getMessage(), e);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return responseBody;
	}

	public String fetchData(String url) {
		String data = null;
		// log.info("请求的url为： " + url);
		if (proxy != null && proxy.toUpperCase().equals(PROXY_IN_USE)) {
			data = getResponseViaProxy(url, proxyHost, proxyPort, proxyProtocol);
			log.info("httpclient 通过代理请求返回 的数据为： " + data);
		} else {
			data = getResponse(url);
			log.info("httpclient 请求返回 的数据为： " + data);
		}
		return data;
	}

	public static String getResponseWithCookies() {
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
				CookiePolicy.IGNORE_COOKIES);

		String responseBody = null;
		try {
			HttpGet httpget = new HttpGet(
					"http://stockapp.finance.qq.com/pstock/view/manage.php?stktype=all&grpid=0&code=sh600132&_r=0.7831246859839733&action=add&uin=43434557");
			ResponseHandler<String> responseHandler = new BasicResponseHandler();

			httpget.setHeader(
					"Cookie",
					"pt2gguin=o0043434557; pgv_pvid=4446940255; pgv_info=ssid=s6407996920; o_cookie=43434557; RECENT_CODE=002104_51%7C%7C; uin=o0043434557; skey=@OE6debdmS; ptisp=cnc; RK=8D6TsvVTEN");

			responseBody = httpclient.execute(httpget, responseHandler);
		} catch (ClientProtocolException e) {

		} catch (IOException e) {

		} finally {
			httpclient.getConnectionManager().shutdown();
		}

		return responseBody;
	}

	public static String getResponseWithCookies(String url, String cookies) {

		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
				CookiePolicy.IGNORE_COOKIES);

		String responseBody = null;
		try {
			HttpGet httpget = new HttpGet(url);
			ResponseHandler<String> responseHandler = new BasicResponseHandler();

			httpget.setHeader("Cookie", cookies);

			responseBody = httpclient.execute(httpget, responseHandler);
		} catch (ClientProtocolException e) {

		} catch (IOException e) {

		} finally {
			httpclient.getConnectionManager().shutdown();
		}

		return responseBody;
	}

	public static String postWithCookies(String url,String cookies,Map<String, String> params) {

		DefaultHttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.RFC_2965);
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("Cookie", cookies);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();		
		if(params!=null){
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				nvps.add(new BasicNameValuePair(key, params.get(key)));
			}
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps));
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity);
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage(), e);
		} catch (ClientProtocolException e) {
			log.error(e.getMessage(), e);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
		return null;
	}

	public static String post(String url, Map<String, String> params) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		String body = null;

		log.info("create httppost:" + url);
		HttpPost post = postForm(url, params);

		body = invoke(httpclient, post);

		httpclient.getConnectionManager().shutdown();

		return body;
	}

	private static String invoke(DefaultHttpClient httpclient,
			HttpUriRequest httpost) {

		HttpResponse response = sendRequest(httpclient, httpost);
		String body = paseResponse(response);

		return body;
	}

	private static HttpPost postForm(String url, Map<String, String> params) {

		HttpPost httpost = new HttpPost(url);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();

		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			nvps.add(new BasicNameValuePair(key, params.get(key)));
		}

		try {
			log.info("set utf-8 form entity to httppost");
			httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return httpost;
	}

	private static String paseResponse(HttpResponse response) {
		log.info("get response from http server..");
		HttpEntity entity = response.getEntity();

		log.info("response status: " + response.getStatusLine());
		String charset = EntityUtils.getContentCharSet(entity);
		log.info(charset);

		String body = null;
		try {
			body = EntityUtils.toString(entity);
			log.info(body);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return body;
	}

	private static HttpResponse sendRequest(DefaultHttpClient httpclient,
			HttpUriRequest httpost) {
		log.info("execute post...");
		HttpResponse response = null;

		try {
			response = httpclient.execute(httpost);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}

	public static void main(String[] args) {
		// System.out.println(getResponseWithCookies());
		String cookies = "PHPSESSID=rprcf5ieqm7todtvpo82rle5h4; l_authRtnUrl=%2Fuser%2Fmybet; Hm_lvt_c58936ec5b8f74234a05eb1379c03a13=1346925488046; Hm_lpvt_c58936ec5b8f74234a05eb1379c03a13=1346927180749; CNZZDATA2871616=cnzz_eid=24481269-1346925489-&ntime=1346925489&cnzz_a=10&retime=1346927180835&sin=<ime=1346927180835&rtime=0; __utma=215901633.627819968.1346925489.1346925489.1346925489.1; __utmb=215901633.11.10.1346925489; __utmc=215901633; __utmz=215901633.1346925489.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); 05415adaea770ed941d78005bbd73058=6e44cd22116bc721f3ea0c16451bcc05b1bd9ecea%3A4%3A%7Bi%3A0%3Bs%3A6%3A%22274656%22%3Bi%3A1%3Bs%3A11%3A%2213551254746%22%3Bi%3A2%3Bi%3A2592000%3Bi%3A3%3Ba%3A0%3A%7B%7D%7D";
		//String url = "http://www.gxq.com.cn/user/mybet";
		String url = "http://www.gxq.com.cn/index.php?r=gxqAuction/checkOutAuctionDeal";
		//System.out.println(getResponseWithCookies(url, cookies));
		System.out.println(postWithCookies(url, cookies,null));
	}
}
